package com.boss.salary.service.impl;

import com.boss.common.entity.PageDTO;
import com.boss.common.util.DateUtils;
import com.boss.framework.dto.PaginationDTO;
import com.boss.salary.constant.SystemDictConstant;
import com.boss.salary.dao.IdepartmentInfoDao;
import com.boss.salary.entity.DepartmentInfo;
import com.boss.salary.service.IDepartmentInfoService;
import com.boss.salary.utils.CommonUtils;
import com.boss.sys.utils.SysUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DepartmentInfoServiceImpl implements IDepartmentInfoService {

    /**
     * 引入日志框架常量
     */
    private final static Logger logger = LoggerFactory.getLogger(DepartmentInfoServiceImpl.class);

    @Autowired
    private IdepartmentInfoDao idepartmentInfoDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertDepartmentInfo(DepartmentInfo departmentInfo) {

        //验证是否重名
        Integer count= idepartmentInfoDao.getNumByName(departmentInfo.getDeptName(),departmentInfo.getAgencyId(),departmentInfo.getId());
        List<String> chileCodeList=idepartmentInfoDao.selectDeptCodeByPID(departmentInfo.getParentId(),departmentInfo.getAgencyId());
        if("0".equals(count.toString())) {
            departmentInfo.setId(SysUtils.generateGuid());
            departmentInfo.setCreateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            departmentInfo.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            departmentInfo.setIsDeleted(SystemDictConstant.IS_FALSE);

            //设置节点
            departmentInfo.setIsLeaf(SystemDictConstant.IS_TRUE);

            int num = idepartmentInfoDao.getNumByLevel1(departmentInfo.getAgencyId());
            DepartmentInfo department = null;
            int parNum = 0;
            //通过父id查询父部门
            if (!StringUtils.isEmpty(departmentInfo.getParentId())) {
                department = idepartmentInfoDao.getDepartmentInfoById(departmentInfo.getParentId());
                //通过父id查询属部门已有数
                parNum = idepartmentInfoDao.getNumByParentId(departmentInfo.getParentId(),departmentInfo.getAgencyId());
            }

            String code = "";
            String parCode="";
            if (StringUtils.isEmpty(department)) {
                if (num > 0) {
                    num = num + 1;
                    code = String.format("%03d", num);
                } else {
                    code = "001";
                }
                departmentInfo.setLevelNo(SystemDictConstant.IS_SUBMIT);
            } else {
                //获取父部门编码
                 parCode = department.getDeptCode();
                code = parCode + String.format("%03d", parNum + 1);
            }
            code=creatDeptCode(chileCodeList,code,parCode,0);
            departmentInfo.setDeptCode(code);
            //判断父id是否有值
            if(StringUtils.isEmpty(departmentInfo.getParentId())){
                departmentInfo.setParentId(SystemDictConstant.NO_SUBMIT);
            }
            idepartmentInfoDao.insertDepartmentInfo(departmentInfo);
            if (!StringUtils.isEmpty(department)) {
                department.setIsLeaf(SystemDictConstant.IS_FALSE);
                idepartmentInfoDao.updateDepartmentInfo(department);
            }
            return "200";
        }
        return "500";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDepartmentInfo(String id) {
        idepartmentInfoDao.deleteDepartmentInfo(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateDepartmentInfo(DepartmentInfo departmentInfo) {

        //验证是否重名
        Integer count= idepartmentInfoDao.getNumByName(departmentInfo.getDeptName(),departmentInfo.getAgencyId(),departmentInfo.getId());
        DepartmentInfo oldDepartment = idepartmentInfoDao.getDepartmentInfoById(departmentInfo.getId());
        if("0".equals(count.toString())) {
            departmentInfo.setUpdateTime(String.valueOf(DateUtils.getCurrentTimeStamp()));
            if (!StringUtils.isEmpty(departmentInfo.getParentId())) {
                departmentInfo.setLevelNo("");
            } else {
                departmentInfo.setLevelNo("1");
                departmentInfo.setParentId("0");
            }
            DepartmentInfo department = null;
            if (!"0".equals(departmentInfo.getParentId())) {
                department = idepartmentInfoDao.getDepartmentInfoById(departmentInfo.getParentId());
            }
            if(!StringUtils.isEmpty(departmentInfo.getParentId())&&!StringUtils.isEmpty(oldDepartment.getParentId())
                    &&!departmentInfo.getParentId().equals(oldDepartment.getParentId())){
                int num = idepartmentInfoDao.getNumByLevel1(departmentInfo.getAgencyId());
                int parNum = 0;
                //获取单位现有编码
                List<String> chileCodeList=idepartmentInfoDao.selectDeptCodeByPID(departmentInfo.getParentId(),departmentInfo.getAgencyId());
                //通过父id查询父部门
                if (!StringUtils.isEmpty(departmentInfo.getParentId())) {
                    //通过父id查询属部门已有数
                    parNum = idepartmentInfoDao.getNumByParentId(departmentInfo.getParentId(),departmentInfo.getAgencyId());

                }
                String code = "";
                String parCode = "";
                if (StringUtils.isEmpty(department)) {
                    if (num > 0) {
                        num = num + 1;
                        code = String.format("%03d", num);
                    } else {
                        code = "001";
                    }
                    departmentInfo.setLevelNo(SystemDictConstant.IS_SUBMIT);
                } else {
                    //获取父部门编码
                    parCode = department.getDeptCode();
                    code = parCode + String.format("%03d", parNum + 1);
                }
                code=creatDeptCode(chileCodeList,code,parCode,0);
                departmentInfo.setDeptCode(code);
            }

            idepartmentInfoDao.updateDepartmentInfo(departmentInfo);
            if (!StringUtils.isEmpty(department)) {
                department.setIsLeaf(SystemDictConstant.IS_FALSE);
                idepartmentInfoDao.updateDepartmentInfo(department);
            }
            return "200";
        }
        return "500";
    }
    private String creatDeptCode(List<String> chileCodeList,String code,String parCode,int parNum){
        if(chileCodeList.contains(code)){
            parNum++;
            code = parCode + String.format("%03d",parNum );
            return creatDeptCode(chileCodeList,code,parCode,parNum);
        }
        return code;
    }

    @Override
    public PageDTO<DepartmentInfo> queryDepartmentInfoPage(PaginationDTO paginationDTO,Map<String, Object> queryParam,List<String> childrenId) {

         List<DepartmentInfo> departmentInfos = idepartmentInfoDao.queryDepartmentInfoPage(paginationDTO,queryParam,childrenId);
         int  total = idepartmentInfoDao.queryDepartmentInfo(queryParam,childrenId);

        PageDTO<DepartmentInfo> pageDTO = new PageDTO<>();
        pageDTO.setRows(departmentInfos);
        pageDTO.setTotal(total);
        return pageDTO;
    }

    @Override
    public List<Map<String, String>> getBaseDataSelect(String parameters) {

        return idepartmentInfoDao.getBaseDataSelect(parameters);
    }

    @Override
    public List<DepartmentInfo> getAllDepartment(String agencyid,String mofDivCode) {
        return idepartmentInfoDao.getAllDepartment(agencyid,mofDivCode);
    }

    @Override
    public List<String> getChildrenId(String deptid,String agencyid,String mofDivCode) throws IOException, ClassNotFoundException {
        List<String> childrenList = new ArrayList<>();
        List<DepartmentInfo> allDepartment = idepartmentInfoDao.getAllDepartment(agencyid,mofDivCode);
        if(allDepartment.size()>0){
            childrenList=getsearchChildrenId(allDepartment,deptid);
        }
        return childrenList;
    }

    @Override
    public DepartmentInfo getDepartmentInfoById(String id) {
        return idepartmentInfoDao.getDepartmentInfoById(id);
    }

    public List<String> getsearchChildrenId(List<DepartmentInfo>list,String deptid) throws IOException, ClassNotFoundException{

        List<String> childrenIds = new ArrayList<>();
        if(list.size()>0){
            for (int i = 0; i < list.size(); i++) {
                DepartmentInfo departmentInfo=list.get(i);
                if(deptid.equals(departmentInfo.getId())){
                    childrenIds.add(departmentInfo.getId());
                }else if(deptid.equals(departmentInfo.getParentId())){
                    childrenIds.add(departmentInfo.getId());

                         List<DepartmentInfo> childrenInfos= CommonUtils.deepCopy(list);
                         childrenInfos.remove(departmentInfo);
                        childrenIds.addAll(getsearchChildrenId(childrenInfos,departmentInfo.getId()));

                }
            }
        }
       return childrenIds;
    }
}
